/**
 * 请求前缀，后面后台添加网关后需要前缀选择微服务
 */
import { fallbackRequestGet } from '@/utils/Request'
import { ResultCode } from '@/constants/constants'
import { uploadFileAutoErr } from '@/api/ApiQiNiu'
import * as QiNiu from 'qiniu-js'

const URL_PREFIX = 'middle-goods/'

/**
 * 获取一个上传图片的token
 * @param {Function} successCallback 成功回调，参数为data
 * @param {Function} fullCallback 肯定触发的回调，先于callback
 */
export const createUploadToken = (successCallback = null, fullCallback = null) => {
  return fallbackRequestGet(URL_PREFIX + 'file-collection/createUploadToken', {}, {}, true, data => {
    if (successCallback) {
      successCallback(data)
    }
  }, null, fullCallback)
}

/**
 * 上传一个文件，自动获取token
 * @param {*} file 文件
 * @param {String} name 文件分类名
 * @param {Function} next 进度回调
 * @param {Function} successCallback 成功回调，参数为data
 * @param {Function} errorCallback 失败回调
 */
export const uploadCollectionFile = (file, name = '', next = null, successCallback = null, errorCallback = null) => {
  createUploadToken(data => {
    if (data && data.code === ResultCode.OK) {
      data = data.object
      const config = {
        useCdnDomain: true,
        region: QiNiu['region'].z2
      }
      const putExtra = {
        params: {
          'x:param1': name
        }
      }
      uploadFileAutoErr(file, data['fileName'], data.token, putExtra, config, next, successCallback, errorCallback)
    }
  })
}
